const { requestGet } = require("./internet");
const { loadLocalConfig, writeHtml, loadLocalHtml } = require("./local");

async function loadContentJson(href, tag, type, refresh) {
    const data = await loadContent(href, tag, type, refresh);
    var parse;
    try {
        parse = require('../parse/' + tag);
        // parse = require('../parse/sfxit');
    } catch (error) {
        console.log(error);
        throw Error('package不包含此方法-' + tag + ', ' + type);
    }
    if (parse[type]) {
        const result = await parse[type](data, tag);
        return result;
    } else {
        // console.log('不包含此方法');
        throw Error('package不包含此方法-' + tag + ', ' + type);
    }
}

async function loadContent(href, tag, type, refresh) {
    if (refresh) {
        return await loadDateForInternet(href, tag, type)
    } else {
        var data = loadLocalHtml(makeFileName(href, tag, type))
        if (data) return data;
        return await loadDateForInternet(href, tag, type);
    }
}


async function loadDateForInternet(href, tag, type) {
    const host = loadHost(tag);
    if (!host) {
        throw Error('没有此类型的host -' + tag);
    }
    const url = joinUrl(host, href);
    var map = { 'Referer': host };
    var data = await requestGet(decodeURI(url), map);
    // console.log(data);
    if (!data || data.error) {
        throw data.error;
    } else {
        writeHtml(data, makeFileName(href, tag, type));
    }
    return data;
}

function makeFileName(href, tag, type) {
    if (href.startsWith('http://') || href.startsWith('https://')) {
        var index = href.lastIndexOf('/');
        return tag + type + href.substring(index + 1)
    }
    return tag + type + href.replace(/\//g, '-').replace(/(\.html)|\?|\=/g, '');
}

function joinUrl(host, href) {
    if (href.startsWith('http')) {
        return href;
    }
    // console.log(host, '--->host');
    if (host.endsWith('/')) {
        host = host.substring(0, host.length - 1)
    }
    if (!href.startsWith('/')) {
        href = '/' + href;
    }
    return host + href;
}

function loadHost(tag) {
    var config = loadLocalConfig(tag)
    if (config) {
        var host = config.host;
        return host;
    }
    return undefined;
}


module.exports = { loadContent, joinUrl, loadContentJson }